package  
{
	import org.flixel.*;
	
	/**
	 * ...
	 * @author Thomas Liu
	 */
	public class Player extends FlxSprite
	{
		public const slowdownSpeed:Number = 50;
		public const jumpVelocity:Number = -80;
		public const speedPerKey:Number = 7;		
		
		[Embed (source = "../data/Chickens/AfroHen.png")] protected var player_hen1_img:Class;
		[Embed (source = "../data/Chickens/BBCock.png")] protected var player_cock_img:Class;
		[Embed (source = "../data/Chickens/VRooster.png")] protected var player_rooster_img:Class;
		[Embed (source = "../data/Chickens/WhiteHen.png")] protected var player_hen2_img:Class;
		
		public var characterImages:Array = [player_hen1_img, player_cock_img, player_rooster_img, player_hen2_img];
		
		// Which keys are bound to up,down,left,right
		public var controls:Object = { };
		
		// The Y coordinate that represents the ground for this chicken (different for each player
		// because of perspective)
		public var baseY:Number = 0;
		
		// The id of the player so that they have different controls and such
		public var playerId:int = 0;
		
		public function Player(x:int, y:int, playerId:int, char:int) 
		{
			super(x, y);
			baseY = y;
			this.playerId = playerId;
			loadGraphic(characterImages[char], true, true, 32, 32);
			
			// Give different controls based on player number
			if (playerId == 0)
			{
				controls["LEFT"] = "LEFT";
				controls["RIGHT"] = "RIGHT";
				controls["UP"] = "UP";
				controls["DOWN"] = "DOWN";
			}
			else if (playerId == 1)
			{
				controls["LEFT"] = "A";
				controls["RIGHT"] = "D";
				controls["UP"] = "W";
				controls["DOWN"] = "S";
			}			
			velocity.x = 0;
			acceleration.y = 200;
		}
		
		override public function update():void 
		{
			updateInput();

			// Decelerate slowly
			if (velocity.x > 1) {	
				acceleration.x = -slowdownSpeed;
			}
			else	// Prevents the chicken from moving backwards if you are stopped
			{
				velocity.x = 0;
				acceleration.x = 0;				
			}
			
			// Prevent the chicken from falling forever
			if (y > baseY && velocity.y > 0)
			{
				y = baseY;
				velocity.y = 0;
			}
			
			super.update();
		}
		
		public function updateInput(): void {
			// Accelerate the chicken when the user taps left and right
			// TODO: make this require some sort of accelerating rhythm.
			// TODO: make this require alternating left and right
			if (FlxG.keys.justPressed(controls["LEFT"])) {
				velocity.x += speedPerKey;
			} else if (FlxG.keys.justPressed(controls["RIGHT"])) {
				velocity.x += speedPerKey;
			} 
			if (FlxG.keys.justPressed(controls["UP"]) && y >= baseY) {
				velocity.y = jumpVelocity;
			}
		}
	
	}

}